//
//  STStatusPictureView.m
//  OCVVeibo
//
//  Created by leergou on 16/7/27.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

#import "STStatusPictureView.h"
#import "STStatusPictureViewCell.h"
#import "STStatusPictureInfo.h"
#import "UIImage+GIF.h"


static NSString *statusPictureViewCell = @"statusPictureViewCell";

static CGFloat cellWidth = 80;
static CGFloat cellMargin = 5;

@interface STStatusPictureView ()<UICollectionViewDataSource>

@end

@implementation STStatusPictureView

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    
    if (self = [super initWithFrame:frame collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]]) {
        
        [self setupUI];
    }
    return self;
}

#pragma mark - collectionView delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.statusPictureList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    STStatusPictureViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:statusPictureViewCell forIndexPath:indexPath];
  
    cell.pictureInfo = self.statusPictureList[indexPath.item];
 
    return cell;
}

#pragma mark - setupUI
- (void)setupUI{
    self.backgroundColor = [UIColor grayColor];
    // 设置 layout
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    layout.itemSize = CGSizeMake(cellWidth, cellWidth);
    layout.minimumInteritemSpacing = cellMargin;
    layout.minimumLineSpacing = cellMargin;
    self.dataSource = self;
    // 注册 cell
    [self registerClass:[STStatusPictureViewCell class] forCellWithReuseIdentifier:statusPictureViewCell];
}

#pragma mark - 重写 set 方法,给内部视图赋值
- (void)setStatusPictureList:(NSArray<STStatusPictureInfo *> *)statusPictureList{
    _statusPictureList = statusPictureList;
    
    // 计算Size
    CGSize size = [self getPictureViewSize:statusPictureList.count];
    // 更新当前约束
    [self updateConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(size);
    }];
    [self reloadData];
    
}

// 计算 pictureViewSize
- (CGSize)getPictureViewSize:(NSInteger)count{
    
    // 计算行数 和 列数
    NSInteger col = count == 4 ? 2 : (count >= 3 ? 3 : count);
    NSInteger row = count == 4 ? 2 : ((count - 1) / 3 + 1);
    // 计算 size
    NSInteger width = cellWidth * col + (col - 1) * cellMargin;
    NSInteger height = cellWidth * row + (row - 1) * cellMargin;
    return CGSizeMake(width, height);
}


@end
